package org.ala.tiktools.sharddb.db;

import javax.sql.DataSource;

import org.ala.tiktools.logs.LoggerFactory;
import org.ala.tiktools.sharddb.Namespace;
import org.ala.tiktools.sharddb.db.provider.ShardDatasourceProvider;
import org.slf4j.Logger;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;


/**
 * 分库组件
 * <p>  没有继承自spring的AbstractRoutingDatasource，因为太麻烦了
 * <p>  而且它也就给你包了一层map，我还不如自己包，还能兼容自己的配置信息
 *
 * @author ala
 * @date 2024-12-27 10:32
 */
public class ShardDatasource extends AbstractRoutingDataSource {


    static Logger log = LoggerFactory.getLogger("tiktools", "sharddb");


    /**
     *  配置信息
     */
    protected ShardDatasourceProvider provider;

    @Override
    public void afterPropertiesSet() {
        //  断掉父类的初始化
//        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return ThreadLocalLookupKey.getLookup();
    }

    public DataSource getDataSource() {
        return determineTargetDataSource();
    }

    @Override
    protected DataSource determineTargetDataSource() {
        Object key = determineCurrentLookupKey();
        if (key == null) {
            return provider.getDatasource(Namespace.SHARD_DATASOURCE_DEFAULT);
        }
        return provider.getDatasource(key.toString());
    }

    public ShardDatasourceProvider getProvider() {
        return provider;
    }

    public void setProvider(ShardDatasourceProvider provider) {
        this.provider = provider;
    }
}
